package com.hb.game.pk.thread;

import android.app.DownloadManager;
import android.database.Cursor;

import com.hb.game.pk.event.DownLoadEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.Timer;
import java.util.TimerTask;

public class DownLoadThread extends Thread {
    private DownloadManager.Query query;
    private DownloadManager downloadManager;
    private long downloadId;
    Timer timer;

    public DownLoadThread(long downloadId, DownloadManager downloadManager, DownloadManager.Query query) {
        this.downloadId = downloadId;
        this.downloadManager = downloadManager;
        this.query = query;
    }

    @Override
    public void run() {
        super.run();
        timer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                queryProgress();
            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    private void queryProgress() {
        if (downloadManager != null) {
            Cursor cursor = downloadManager.query(query.setFilterById(downloadId));
            int bytesDownload = -1;
            int bytesTotal = 0;
            if (cursor != null && cursor.moveToFirst()) {
                String address = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                //已经下载的字节数
                bytesDownload = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                bytesTotal = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
//                String title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
//                String description = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION));
//                long downloadId = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
//                String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI));
//                int progress = bytesDownload * 100 / bytesTotal;
            }
            if (cursor != null) {
                cursor.close();
            }
            if (bytesTotal == bytesDownload) {
                timer.cancel();
                EventBus.getDefault().post(new DownLoadEvent());
            }
        }
    }
}
